/**
 * @function 博文模块api
 * @author anytao
 * @created 2016-07-18
 * @version 1.0
 */
'use strict';
import Base from './base.js';
export default class extends Base {

    /**
     * 博文列表页数据接口
     */
    async listAction() {

        let search = this.post();
        let query = {};
        let order = {};

        if (!think.isEmpty(search.title)) {
            query.title = ['like', '%' + search.title + '%'];
        }

        let articles = await this.model('article')
            .order(order)
            .where(query)
            .page(this.post('pageCurrent'), this.post('pageSize') || 15)
            .countSelect();

        articles.pageCurrent = articles.currentPage;
        articles.total = articles.count;
        articles.list = articles.data;
        delete articles.data;

        return this.json(articles);
    }

    /**
     * 博文新增编辑接口
     */
    async editAction() {

        let result = {
            "statusCode": "200",
            "message": "新增成功",
            "tabid": "table, table-fixed",
            "closeCurrent": true,
            "forward": "",
            "forwardConfirm": "",
            "id": 0,
            'type': 'update' //新增or编辑
        };

        let articleId = 0;
        let article = this.post();
        if (article.id == 0) {
            result.type = 'add';
            article.id = null;
            article.created_at = think.datetime();
            articleId = await this.model('article').add(article);
            result.id = articleId;
        } else {
            result.message = '编辑成功';
            article.updated_at = think.datetime();
            articleId = await this.model('article').where({
                id: article.id
            }).update(article);
            result.id = article.id;
        }
        return this.json(result);
    }

    /**
     * 博文删除接口
     */
    async deleteAction() {

        let articleIds = this.post('articleIds');
        let result = {
            statusCode: '200',
            message: '删除成功',
            articleIds: articleIds
        }

        let deleteMsg = await this.model('article').where({
            id: ["IN", articleIds]
        }).delete();
        return this.json(result);
    }

    /**
     * 单条记录
     * 编辑时调用
     */
    async getAction() {

        let article = {
            id: '0'
        };

        let articleId = this.get('articleId');

        if (articleId) {

            article = await this.model('article').where({
                id: articleId
            }).find();
        }
        return this.json(article);
    }
}